<template>
  <el-container class="schedule-page">
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="aside">
      <div class="profile">
        <el-avatar :size="60" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
      </div>
      <el-menu :default-active="activeMenu" @select="handleMenuSelect">
        <el-menu-item index="schedule">
          <div class="menu-item-content">
            <i class="el-icon-date icon"></i>
            <span class="menu-span">Schedule</span>
          </div>
        </el-menu-item>
        <el-menu-item index="tasks">
          <div class="menu-item-content">
            <i class="el-icon-document icon"></i>
            <span class="menu-span">Task</span>
          </div>
        </el-menu-item>
      </el-menu>
      <!-- 数据库选择区域 -->
      <div class="database-section">
        <div id="database-head">
          <h4 class="database-title">Databases</h4>
          <el-button
            icon="el-icon-plus"
            class="icon-only-btn"
            @click="openCreateDatabaseDialog"
          ></el-button>
        </div>
        <ul class="database-list">
          <li
            v-for="(db, index) in sortedDatabases"
            :key="index"
            @click="selectDatabase(db)"
            :class="{ active: selectedDatabase === db }"
          >
            <span style="padding-left: 10px;">{{ db.name }}</span>
          </li>
        </ul>
      </div>
      <!-- 设置按钮 -->
      <div id="setting" @click="toggleSettingsDrawer">
        <i class="el-icon-setting icon"></i>
      </div>
      <div id="space-occupying"></div>
    </el-aside>

    <!-- 主体内容 -->
    <el-container>
      <el-header class="header">
        <h2>{{ pageTitle }}</h2>
      </el-header>

      <el-main class="main-content">
        <el-row :gutter="10">
          <!-- 左侧：日历 -->
          <el-col :span="18">
            <el-calendar v-model="selectedDate" :first-day-of-week="1">
              <template slot="dateCell" slot-scope="{ data }">
                <div
                  :style="{
                    background: hasTask(data.day) ? '#e6f7ff' : 'transparent',
                    borderRadius: '6px',
                    padding: '5px',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }"
                >
                  <p :style="{ color: hasTask(data.day) ? 'red' : 'inherit' }">
                    {{ data.day.split('-').slice(2).join('-') }}
                  </p>
                </div>
              </template>
            </el-calendar>
          </el-col>

          <!-- 右侧：任务列表 -->
          <el-col :span="5">
            <div class="task-list">
              <h3>{{ formatDate(selectedDate) }}'s Tasks</h3>
              <add-task-button
                :selectedDate="formatDate(selectedDate)"
                @task-added="addTask"
              />
              <el-divider></el-divider>
              <ul class="tasks">
                <li
                  v-for="(task, index) in tasksForSelectedDate"
                  :key="index"
                  :class="['task-card', getPriorityClass(task.priority)]"
                  @click="showTaskDetail(task)"
                >
                  <div class="task-content">
                    <div class="task-name">{{ task.name }}</div>
                    <div class="task-time">
                      {{ task.startTime }} - {{ task.endTime }}
                    </div>
                    <div>Priority: {{ getPriorityText(task.priority) }}</div>
                  </div>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </el-main>

      <!-- 整个页面右侧的设置侧边栏 -->
      <settings-drawer
        v-if="selectedDatabase && selectedDatabase.name"
        :visible.sync="isSettingsDrawerVisible"
        :selectedDatabase="selectedDatabase"
        @update:visible="isSettingsDrawerVisible = $event"
        @update:name="updateDatabaseName"
        @delect:database="delectDatabase"
      />
    </el-container>
    <!-- 创建数据库的弹窗 -->
    <el-dialog
      title="Create Database"
      :visible.sync="isCreateDatabaseDialogVisible"
      width="400px"
      @close="closeCreateDatabaseDialog"
    >
      <el-form :model="newDatabase" ref="createDatabaseForm" label-width="55px">
        <el-form-item label="Name" prop="name">
          <el-input
            v-model="newDatabase.name"
            placeholder="Enter database name"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="newDatabase" ref="createDatabaseForm" label-width="55px">
        <el-form-item label="Link" prop="link">
          <el-input
            v-model="subscriptionLink"
            placeholder="Enter subscription link (optional)"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCreateDatabaseDialog">Cancel</el-button>
        <el-button type="primary" @click="createDatabase">Create</el-button>
      </span>
    </el-dialog>

    <!-- 任务详情浮窗 -->
    <el-dialog
      title="Task Details"
      :visible.sync="isTaskDetailVisible"
      width="500px"
      custom-class="task-dialog"
      @close="closeTaskDetail"
    >
      <div v-if="currentTask" class="task-dialog-content">
        <p><strong>Task Name:</strong> {{ currentTask.name }}</p>
        <p><strong>Start Time:</strong> {{ currentTask.startTime }}</p>
        <p><strong>End Time:</strong> {{ currentTask.endTime }}</p>
        <p><strong>Priority:</strong> 
          <span :class="getPriorityClass(currentTask.priority)">
            {{ getPriorityText(currentTask.priority) }}
          </span>
        </p>
        <p><strong>Task Details:</strong></p>
        <p class="task-detail">{{ currentTask.details || "No details provided." }}</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="markTaskAsCompleted(currentTask)" type="primary">Mark as Completed</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import locale from "element-ui/lib/locale";
  import lang from "element-ui/lib/locale/lang/en";
  import SettingsDrawer from "@/components/SettingsDrawer.vue";
  import addTask from "@/components/addTask.vue";
  import { getDatabase } from "../api/getDatabase";
  import { changeDatabase } from "../api/changeDatabase";
  import { createDatabase } from "../api/createDatabase";
  import { createDatabaseWithics } from "../api/createDatabaseWithics";
  import { delDatabase } from "../api/delDatabase";
  import { getTask } from "../api/getTask";
  import { createTask } from "../api/createTask";
  import { updateTask } from "../api/updateTask";

  locale.use(lang);

  export default {
    data() {
      return {
        selectedDate: new Date(),
        tasks: [], // 存储所有任务
        activeMenu: "schedule",   // 默认选中的菜单
        pageTitle: "Schedule Management",   // 默认页面标题
        isSettingsDrawerVisible: false,  // 控制设置侧边栏
        isTaskDetailVisible: false, // 控制任务详情浮窗
        currentTask: null, // 存储当前任务详情
        databases: [],
        subscriptionLink: "", // 订阅链接
        selectedDatabase: null,
        isCreateDatabaseDialogVisible: false, // 控制创建数据库弹窗的显示
        newDatabase: {name: ""}, // 新数据库信息
      };
    },
    components: {
      SettingsDrawer,
      addTaskButton: addTask,
    },
    computed: {
      sortedDatabases() {
        return this.databases.sort((a, b) => a.name.localeCompare(b.name));
      },
      tasksForSelectedDate() {
        // 筛选出当前日期小于结束日期的任务且大于开始日期的任务
        let today = this.formatDate(new Date(this.selectedDate));
          
        return this.tasks.filter(
          (task) =>
            task.status === 0 &&
            this.formatDate(new Date(task.startTime)) <= today &&
            this.formatDate(new Date(task.endTime)) >= today
        );
      },
    },
    created() {
      this.initData();
    },
    methods: {
      async initData() {
        try {
          // 使用 await 等待异步操作完成
          const res = await getDatabase();
          let sel = res.data[res.data.length-1];
          res.data.pop();
          this.databases = res.data.map((name) => ({
            name: name.endsWith('.json') ? name.replace(/\.json$/, '') : name,
          }));

          // 设置默认选中数据库
          this.selectedDatabase = this.databases.find((db) => db.name === sel) || this.databases[0];
          // 获取任务列表
          const taskRes = await getTask(this.selectedDatabase.name);


          // 将任务列表存储到 tasks 中
          this.tasks = taskRes.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));

          
        } catch (error) {
          console.error('Error fetching databases:', error);
          this.databases = [];
          this.selectedDatabase = null;
        }
      },
      // 更新数据库名称
      async updateDatabaseName(newName) {
        // 判断是否存在同名数据库
        if (this.databases.some((db) => db.name === newName)) {
          this.$message.error(`Database "${newName}" already exists!`);
          return;
        }
        const res = await changeDatabase(this.selectedDatabase.name, newName);
        // console.log(res);
        
        if (res.status === 200) {
          // 更新数据库列表中的数据库名称
          this.databases = this.databases.map((db) => {
            if (db.name === this.selectedDatabase.name) {
              db.name = newName;
            }
            return db;
          });
          this.selectedDatabase.name = newName;
          this.$message.success(`Database name has been updated to: ${this.selectedDatabase.name}`);
        } else {
          this.$message.error("Failed to update database name!");
        }
      },
      // 删除数据库
      async delectDatabase() {
        const res = await delDatabase(this.selectedDatabase.name);
        if(res.status==200){
          this.databases = this.databases.filter((db) => db.name !== this.selectedDatabase.name);
          this.selectedDatabase = this.databases[0] || null;
          // 关闭设置侧边栏
          this.isSettingsDrawerVisible = false;
          this.$message.success("Database deleted successfully!");
          // 请求任务列表
          const res = await getTask(this.selectedDatabase.name);
          this.tasks = res.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));
        }else{
          this.$message.error("Failed to delete database!");
        }
      },
      // 打开创建数据库弹窗
      openCreateDatabaseDialog() {
        this.newDatabase.name = ""; 
        this.isCreateDatabaseDialogVisible = true;
      },
      // 关闭创建数据库弹窗
      closeCreateDatabaseDialog() {
        this.isCreateDatabaseDialogVisible = false;
      },
      // 创建数据库
      async createDatabase() {
        if (!this.newDatabase.name.trim()) {
          this.$message.error("Database name cannot be empty!");
          return;
        }
        // 判断数据库名称是否已存在
        if (this.databases.some((db) => db.name === this.newDatabase.name.trim())) {
          this.$message.error(`Database "${this.newDatabase.name}" already exists!`);
          return;
        }
        let a;
        // 判断link是否为空
        if(this.subscriptionLink.trim() === ""){
          // 使用正常的创建数据库请求
          const res = await createDatabase(this.newDatabase.name.trim());
          a = res;
        }else{
          const res = await createDatabaseWithics(this.subscriptionLink.trim() , this.newDatabase.name.trim());
          a = res;
        }
        if(a.status === 200){
          const newDb = { name: this.newDatabase.name.trim() };
          this.databases.push(newDb); // 添加到数据库列表
          this.$message.success(`Database "${newDb.name}" created successfully!`);
          this.closeCreateDatabaseDialog(); // 关闭弹窗
          this.selectedDatabase = newDb; // 选中新创建的数据库
          // 请求任务列表
          const res = await getTask(this.selectedDatabase.name);
          this.tasks = res.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));
        }else{
          this.$message.error("Failed to create database!");
        }

        this.subscriptionLink = ""; // 清空订阅链接
        

      },
      async selectDatabase(db) {
        if (this.selectedDatabase === db) {
          return;
        }
        const res = await getTask(db.name);

        this.tasks = res.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));
        
        this.selectedDatabase = db;
        this.$message.success(`Selected Database: ${db.name}`);
      },
      hasTask(date) {
        const formattedDate = this.formatDate(new Date(date)); // 日历中的日期
        // 判断是否存在未完成的任务
        const hasIncompleteTask = this.tasks.some((task) => {
          const taskStart = this.formatDate(new Date(task.startTime));
          const taskEnd = this.formatDate(new Date(task.endTime));
          return (
            task.status === 0 && // 未完成的任务
            formattedDate >= taskStart &&
            formattedDate <= taskEnd
          );
        });
        return hasIncompleteTask;
      },
      // 格式化日期
      formatDate(date) {
        const d = new Date(date);
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
          d.getDate()
        ).padStart(2, "0")}`;
      },
      async addTask(newTask) {
        const formatDate = (date) => {
          const d = new Date(date);
          const year = d.getFullYear();
          const month = (d.getMonth() + 1).toString().padStart(2, '0'); 
          const day = d.getDate().toString().padStart(2, '0');
          const hours = d.getHours().toString().padStart(2, '0');
          const minutes = d.getMinutes().toString().padStart(2, '0');
          const seconds = d.getSeconds().toString().padStart(2, '0');
          return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
        };
        let task = {
          id: newTask.id,
          task_Id: newTask.name,
          index_Id: this.selectedDatabase.name,
          start_Date: formatDate(newTask.startTime),
          end_Date: formatDate(newTask.endTime),
          priority: newTask.priority,
          details: newTask.details,
          status: newTask.status,
        };

        let task_put = JSON.stringify(task);
        // console.log(task_put);

        // 添加任务
        const res = await createTask(task_put);
        if (res.status === 200) {
          this.tasks.push(newTask);
          this.$message.success("Task added successfully!");
        } else {
          this.$message.error("Failed to add task!");
        }
      },

      getPriorityText(priority) {
        // 将数值优先级转回文本用于展示
        const priorityText = {
          3: "Major",
          2: "Minor",
          1: "Common",
        };
        return priorityText[priority] || "Major";  
      },
      handleMenuSelect(key) {
        this.activeMenu = key;
        switch (key) {
          case "schedule":
            break;
          case "tasks":
            this.$router.push("/task");
            break;
        }
      },
      toggleSettingsDrawer() {
        this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible;
      },
      showTaskDetail(task) {
        this.currentTask = task;
        this.isTaskDetailVisible = true;
      },
      // 关闭任务详情
      closeTaskDetail() {
        this.isTaskDetailVisible = false;
        this.currentTask = null;
      },
      // 标记任务为已完成
      async markTaskAsCompleted(task) {
        if (task && task.status !== 1) {
          this.$confirm("Are you sure the task is complete?", "Prompt", {
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            type: "warning",
          })
            .then(async () => {
              let Task = {
                id: task.id,
                task_Id: task.name,
                index_Id: this.selectedDatabase.name,
                start_Date: task.startTime,
                end_Date: task.endTime,
                priority: task.priority,
                details: task.details,
                status: 1,
              };
              let task_put = JSON.stringify(Task);
              const res = await updateTask(task_put); 
              
              if (res.status ==200){
                task.status = 1; // 将任务状态设置为已完成
                this.$message({
                  message: `Task "${task.name}" marked as completed!`,
                  type: "success",
                });
                this.closeTaskDetail(); // 关闭详情弹窗
              }else{
                this.$message.error("Failed to mark task as completed!");
              }
            })
            .catch(() => {
              this.$message.info("Canceled marking task as completed.");
            });
        }else{
          this.$message.error("Task has been completed!");
        }
      },
      // 获取优先级对应的 CSS 类名
      getPriorityClass(priority) {
        const classes = {
          3: "priority-major",
          2: "priority-minor",
          1: "priority-common",
        };
        return classes[priority] || "priority-major";
      },
      // 获取优先级文本
      getPriorityText(priority) {
        const priorityText = {
          3: "Major",
          2: "Minor",
          1: "Common",
        };
        return priorityText[priority] || "Major";
      },
    },
  };
</script>
  
<style scoped>
  .schedule-page {
    height: 100vh;
    display: flex;
    overflow: hidden;
  }

  .aside {
    background-color: #f4f5f7;
    padding-top: 20px;
    text-align: center;
    border-right: 1px solid #dcdfe6;
  }

  .profile {
    margin-bottom: 20px;
  }

  .main-content {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden; 
  }

  .el-row {
    flex: 1;
    display: flex;
    gap: 10px;
    overflow: hidden;
  }

  .el-calendar {
    height: 100%;
    border-radius: 8px;
    padding-top: 30px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    flex: 1;
    overflow: hidden; 
  }

  .task-list {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    overflow: hidden; 
  }

  .tasks {
    list-style: none;
    padding: 0;
    overflow-y: auto;
    flex: 1;
    margin-bottom: 0 !important;
  }

  .tasks li {
    display: flex;
    align-items: center;
    margin: 10px 0;
    margin-bottom: 25px; 
  }
  .priority-major {
    color: red;
    font-weight: bold;
  }

  .priority-minor {
    color: orange;
  }

  .priority-common {
    color: green;
  }


  .completed {
    text-decoration: line-through;
    color: #c0c4cc;
  }

  .menu-item-content {
    background-color: #f4f5f7;
    display: flex;
    justify-content: flex-start;
    align-items: center; 
    height: 100%;
    padding-left: 35px; 
  }

  .el-menu-item {
    margin-right: 0 !important;
    height: 70px;
    text-align: center;
    padding: 0;
  }

  .el-menu-item [class^=el-icon-] {
    margin-right: 0 !important;
    font-size: 30px;
  }

  #setting {
    /* 固定在底部 */
    position: absolute;
    width: 184px;
    bottom: 40px;
    font-size: 50px !important;
    text-align: center;
    color: #909399;
    cursor: pointer;
    background-color: #f4f5f7;
  }
  #space-occupying {
    position: absolute;
    width: 184px;
    bottom: 0;
    height: 40px;
    background-color: #f4f5f7;
  }

  i.el-icon-setting.icon::before {
    font-size: 40px;
  }

  #setting:hover {
    color: #5a9cf8;
  }

  .icon {
    font-size: 24px;
    margin-bottom: 5px;
  }

  .el-menu-item, .el-submenu__title {
    line-height: 10px !important;
  }

  li.el-menu-item {
    padding-left: 0 !important;
    height: 90px !important;
  }

  .menu-span {
    font-size: 18px;
    padding-left: 15px;
  }

  /* 侧边栏 */
  .settings-drawer {
    width: 400px;
  }
  .task-card {
    background-color: #f3f8fd; 
    color: black;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .task-card:hover {
    cursor: pointer;
  }

  .task-content {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .task-name {
    font-size: 18px;
    font-weight: bold;
    color: black !important;
  }

  .task-time {
    font-size: 14px;
    color: #b8bdbf; 
  }

  .tasks::-webkit-scrollbar {
    width: 8px;
  }
  .tasks::-webkit-scrollbar-thumb {
    background-color: #888;
    border-radius: 4px;
  }
  .tasks::-webkit-scrollbar-thumb:hover {
    background-color: #555;
  }

  .el-dialog__header {
    font-size: 18px;
    font-weight: bold;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
  ::v-deep(.el-dialog) {
    border-radius: 15px; 
  }
  .task-dialog .task-dialog-content {
    line-height: 1.8;
    font-size: 14px;
    color: #606266;
  }

  .task-dialog-content p {
    margin-bottom: 10px;
  }

  .task-detail {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 6px;
    border: 1px solid #ebeef5;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 10px;
  }

  .priority-major {
    color: red;
    font-weight: bold;
  }

  .priority-minor {
    color: orange;
  }

  .priority-common {
    color: green;
  }

  /* 数据库选择样式 */
  .database-section {
    margin-top: 60px;
    padding-top: 20px;
    padding-bottom: 10px;
    text-align: left;
  }

  .database-title {
    font-size: 14px;
    color: #909399;
    padding: 0 20px;
    margin-bottom: 10px;
  }

  .database-list {
    margin-top: 20px;
    padding: 0 10px;
    list-style: none; 
    max-height: 380px; 
    overflow-y: auto;
    border-radius: 8px; 
  }

  .database-list li {
    display: block; 
    padding: 10px 15px;
    cursor: pointer;
    color: #606266;
    font-size: 14px; 
    line-height: 1.5; 
    transition: background-color 0.2s ease, color 0.2s ease;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; 
  }


  .database-list li:hover {
    background-color: #f5f7fa;
    border-radius: 8px; 
  }

  .database-list li.active {
    background-color: #e6f7ff; 
    border-radius: 8px; 
    font-weight: bold; 
    color: #409eff;
  }

  .database-list::-webkit-scrollbar {
    width: 8px;
  }

  .database-list::-webkit-scrollbar-thumb {
    background-color: #888; 
    border-radius: 4px; 
  }

  .database-list::-webkit-scrollbar-thumb:hover {
    background-color: #555; 
  }
  .database-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
  }

  .icon-only-btn {
    background-color: transparent;
    color: #909399;
    border: none;
    padding: 0;
    margin-top: 8px;
    margin-right: 10px;
    font-size: 18px;
    cursor: pointer;
    transition: color 0.3s ease;
  }

  .icon-only-btn:hover {
    color: #409eff;
  }
  #database-head{
    display: flex;
    justify-content: space-between;
    align-items: center;

  }



</style>


  